package com.alili_tv.system.exception;

import com.alili_tv.system.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public R<String> doBusinessException(BusinessException e) {
        log.info(e.getMessage());

        return R.error(e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public R<String> doNotLoginException(NotLoginException e) {
        log.info(e.getMessage());
        return R.login(e.getMessage());
    }

    @ExceptionHandler(SystemException.class)
    public R<String> doSystemException(SystemException e) {
        e.printStackTrace();

        return R.error("系统异常，请稍后重试");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> doDuplicateKeyException(DuplicateKeyException e) {
        if (e.getMessage().contains("user.name")) {
            return R.error("用户名已存在");
        } else if (e.getMessage().contains("user.phone")) {
            return R.error("手机号已注册");
        } else if (e.getMessage().contains("user.email")) {
            return R.error("邮箱已注册");
        }
        e.printStackTrace();

        return R.error("系统异常，请稍后重试");
    }

    @ExceptionHandler(Exception.class)
    public R<String> doException(Exception e){
        // 记录日志
        // 发送消息给运维
        // 发送邮件给开发人员,ex对象发送给开发人工
        e.printStackTrace();
        return R.error("系统繁忙, 请稍后再试");
    }

}
